package com.geline.demo.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geline.easyexcel.interfaces.DBExcelCrudConsumer;
import com.geline.easyexcel.utils.BeanFieldUtil;
import com.geline.easytrans.service.EasyTransService;
import com.geline.mybatisplus.util.SQLFieldBsmKeyUtil;
import com.geline.mybatisplus.util.SQLFieldUniqueKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.core.GenericTypeResolver;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.Collection;
import java.util.List;

/**
 * @author: mengxin
 * @date: 2024/1/25 11:41
 */
@Slf4j
public abstract class MPExcelCrudConsumer extends DBExcelCrudConsumer {

    @Autowired
    protected EasyTransService easyTransService;

    public abstract IService getIService(String entityName);

    //处理字典翻译、行政区划翻译
    public abstract void transLabelToKey(Collection entityList);

    //处理字典翻译、行政区划翻译
    public abstract void transKeyToLabel(Collection entityList);

    @Override
    public void saveBatch(Collection entityVOList) {
        if(entityVOList==null || entityVOList.size()==0){
            return;
        }
        // UserVO
        Object entity = entityVOList.stream().findFirst().get();
        String simpleName = entity.getClass().getSimpleName();
        // User
        String entityName = simpleName.substring(0, simpleName.length() - 2);

        //处理字典翻译
        transLabelToKey(entityVOList);

        //数据库操作类
        IService service = this.getIService(entityName);
        Class<?>[] typeArguments = GenericTypeResolver.resolveTypeArguments(service.getClass(), ServiceImpl.class);
        Class doClass = typeArguments[1];
        List doList = BeanUtil.copyToList(entityVOList, doClass);
        doList.stream().forEach(row -> {
            //唯一索引回填id
            fillEntity(row);
            //生成标识码
            SQLFieldBsmKeyUtil.handle(row);
        });
        service.saveBatch(doList);
    }

    protected void fillEntity(Object entity){
        String whereSql = SQLFieldUniqueKeyUtil.createWhereSql(entity, true);
        if(StrUtil.isBlank(whereSql)) {
            // 当业务无唯一标识校验逻辑时，不做以下数据回填操作
            return;
        }
        TableName table = entity.getClass().getAnnotation(TableName.class);
        String sql = String.format("select * from %s where 1=1%s", table.value(), whereSql);
        try {
            Object object = getJdbcTemplate().queryForObject(sql, new BeanPropertyRowMapper(entity.getClass()));
            if(object!=null){
                Object id = BeanUtil.getFieldValue(object, "id");
                //设置id,createdTime,createdBy,deleted
                ReflectUtil.setFieldValue(entity, "id", id);
                if(BeanMap.create(entity).containsKey("createdTime")){
                    ReflectUtil.setFieldValue(entity, "createdTime", BeanUtil.getFieldValue(object, "createdTime"));
                }
                if(BeanMap.create(entity).containsKey("createdBy")){
                    ReflectUtil.setFieldValue(entity, "createdBy", BeanUtil.getFieldValue(object, "createdBy"));
                }
                //导入对旧数据做还原
                if(BeanMap.create(entity).containsKey("deleted")){
                    ReflectUtil.setFieldValue(entity, "deleted", 0);
                }
                //导入时设置默认值String(null->"") Integer(null->0)
                BeanFieldUtil.setDefaultValues(entity, false);
            }
        }catch (EmptyResultDataAccessException | IllegalAccessException e){
            log.warn(e.getMessage());
        }
    }
}
